package comum;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Pacote {
	
	protected String type;
	protected String path;
	protected String content;
	
	public Pacote (String type, String path, String content) {
		this.setType(type);
		this.setPath(path);
		this.setContent(content);
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		if(type.contains("type->")) { type = type.split("->")[1]; }
		this.type = type;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		if(path.contains("path->")) { path = path.split("->")[1]; }
		this.path = path;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		if(content.contains("content->")) { content = content.split("->", 2)[1]; }
		this.content = content;
	}
	
	
	public String getFullMessage() {
		String message = "type->"+this.getType()+"\n";
		message += "path->"+this.getPath()+"\n";
		message += "content->"+this.getContent();
		System.out.println(message);
		return message;
	}
	
	public boolean sendTo(String ip, Integer port) {
		System.out.println("Enviando pacote");
		Socket socket;
		try {
			socket = new Socket(ip, port);
			OutputStream socketOutput = socket.getOutputStream();
			socketOutput.write(this.getFullMessage().getBytes());
			socket.close();
			socketOutput.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
